package com.ycq.httpclient.cookies;

import org.apache.http.HttpResponse;
import org.apache.http.client.CookieStore;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

import java.io.IOException;
import java.util.List;
import java.util.Locale;
import java.util.ResourceBundle;

public class MyCookiesForGet {

    private String url;
    private ResourceBundle bundle;
    private CookieStore store;

    @BeforeTest
    public void beforTest() {
        bundle = ResourceBundle.getBundle("application", Locale.CHINA);
        url = bundle.getString("test.url");
    }

    @Test
    //获取cookies里面的信息
    public void testGetCookies() throws IOException {
        String result;
        //配置文件拼接url
        String uri = bundle.getString("getCookies.url");
        //注意拼接顺序
        String testUrl = this.url + uri;
        //访问
        HttpGet get = new HttpGet(testUrl);
        DefaultHttpClient client = new DefaultHttpClient();
        HttpResponse response = client.execute(get);
        result = EntityUtils.toString(response.getEntity(), "utf-8");
        System.out.println(result);

        this.store= client.getCookieStore();
        List<Cookie> storeCookies = store.getCookies();
        for (Cookie c : storeCookies) {
            String name = c.getName();
            String value = c.getValue();
            System.out.println("name=" + name + ";;;;value=" + value);
        }
    }
    @Test(dependsOnMethods = "testGetCookies")
    public void testGetWithCookies() throws IOException {
        String uti=bundle.getString("get.with.cookies");
        String testurl=this.url+uti;
        HttpGet get=new HttpGet(testurl);
        DefaultHttpClient c=new DefaultHttpClient();
        //设置cookies信息
        c.setCookieStore(this.store);
        //访问
        HttpResponse response = c.execute(get);
        //获取响应码
        int statusCode = response.getStatusLine().getStatusCode();
        System.out.println(statusCode);
        if (statusCode==200){
           String result=EntityUtils.toString(response.getEntity(),"utf-8");
            System.out.println(result);
        }
    }
}
